<template>
  <button @click="sendCodeBtn" class="code">{{ time === 0 ? '发送验证码' : `${time}秒` }}</button>
</template>

<script>
import { ref } from 'vue'
import { useIntervalFn } from '@vueuse/shared'
export default {
  setup() {
    /*
      useIntervalFn
        1. 可通过 { immediate: false } 设置不要立刻执行
        2. 组件卸载的时候会自动清理定时器
        3. resume  启动定时器  /  pause  停止定时器
    */
    const time = ref(0)

    const { resume, pause } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          time.value = 0
          pause()
        }
      },
      100,
      { immediate: false }
    )

    const sendCodeBtn = () => {
      time.value = 30
      resume()
    }

    return { sendCodeBtn, time }
  }
}
</script>

<style>
</style>
